package com.mingqijia.gassafety.job.job.message;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.HistoryAlarmVo;
import com.mingqijia.gassafety.db.entity.vo.HistoryBrokenVO;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.EquipmentType;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;

import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName CreateServiceInfoHistoryJob.java
 * @Description TODO
 * @createTime 2024年01月16日
 */
@Component
@Slf4j
public class CreateAlarmBrokenHistoryJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    HistoryBrokenMapper historyBrokenMapper;
    @Autowired
    AppealHistoryMapper appealHistoryMapper;

    public static final Integer pageSize = 100;

    /**
     *   处理报警记录和故障记录的历史数据，执行一次后删除
     */
    @XxlJob("createAlarmBrokenHistoryJob")
    public ReturnT<String> createServiceInfoHistoryJob(String param) {
        XxlJobLogger.log("XXLJOB-createAlarmBrokenHistoryJob start..." );
        log.info("createAlarmBrokenHistoryJob--start--------");
        String key = Constants.EQUIPMENT_CREATE_SERVICE_INFO;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    execute();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.info("createAlarmBrokenHistoryJob-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("createAlarmBrokenHistoryJob-error:{}", e);
        }
        log.info("createAlarmBrokenHistoryJob--end--------");
        XxlJobLogger.log("XXLJOB-createAlarmBrokenHistoryJob end..." );
        return ReturnT.SUCCESS;
    }

    private boolean execute() {
        //报警信息
        int pageIndex = 1;
        long total = 0;
        do{
            Page<Consumer> pages = PageHelper.startPage(pageIndex, pageSize);
            List<HistoryAlarmVo> records = historyAlarmMapper.getAlarmRecord();
            pageIndex++;
            total = pages.getTotal();
            log.info("createAlarmBrokenHistoryJob-alarm,{},{}", pages.getPages(), pages.getPageSize(), pages.getTotal());
            if (CollectionUtils.isNotEmpty(records)) {
                records.stream().forEach(x -> {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getId,x.getId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarmLog = new HistoryAlarm();
                    historyAlarmLog.setAppealStatus(x.getAppealStatus());
                    historyAlarmLog.setAppealResult(x.getAppealResult());
                    historyAlarmLog.setUserName(x.getUserName());
                    historyAlarmLog.setUserAccount(x.getUserAccount());
                    historyAlarmLog.setAppealTime(x.getAppealTime());
                    historyAlarmLog.setWorkorderId(x.getWorkorderId());
                    historyAlarmMapper.update(historyAlarmLog,historyAlarmWrapper);
                });
            }
            records.clear();
        }while(total > (pageIndex - 1) * pageSize);


        //报警信息
        int brokenPageIndex = 1;
        long brokenTotal = 0;
        Map<Integer, String> consumerIndustryMap = new HashMap<>();
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
        do{
            Page<Consumer> brokenPages = PageHelper.startPage(brokenPageIndex, pageSize);
            List<HistoryBrokenVO> brokenRecords = historyBrokenMapper.getBrokenRecord();
            brokenPageIndex++;
            brokenTotal = brokenPages.getTotal();
            log.info("createAlarmBrokenHistoryJob-broken,{},{}", brokenPages.getPages(), brokenPages.getPageSize(), brokenPages.getTotal());
            if (CollectionUtils.isNotEmpty(brokenRecords)) {
                brokenRecords.stream().forEach(x -> {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getId,x.getId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBrokenLog = new HistoryBroken();
                    historyBrokenLog.setAppealStatus(x.getAppealStatus());
                    historyBrokenLog.setAppealResult(x.getAppealResult());
                    historyBrokenLog.setUserName(x.getUserName());
                    historyBrokenLog.setUserAccount(x.getUserAccount());
                    historyBrokenLog.setAppealTime(x.getAppealTime());
                    historyBrokenLog.setWorkorderId(x.getWorkorderId());
                    historyBrokenMapper.update(historyBrokenLog,historyBrokenWrapper);
                });
            }
            brokenRecords.clear();
        }while(brokenTotal > (brokenPageIndex - 1) * pageSize);


        return true;
    }



}